<?php

namespace Admin\Frontend\Controllers;

use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Assets;
use Helpers\Template;
class SpeakController extends ControllerBase
{

    /**
     * 白名单列表页面
     *
     * create by ck 20170323
     */
    public function replacementsListAction()
    {
        $this->view->pick('speak/replacementsList');
        Assets::easyUI('js/speak/replacementsList.js');
        $this->assets->addJs('assets/jquery/jquery.form.js');
        Main::showNavPosition();
        Template::exists('Speak_Replacements', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listButtonArr = array();
        if(UserPower::checkUserPower('Res_App_Replacements_Add')){
            $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus');
        }
        if(UserPower::checkUserPower('Res_App_Replacements_Del')){
            $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash');
        }
        $this->view->setVars(array(
            'List'       => Template::createList('List', 'Speak_Replacements', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    /**
     * 获取字典白名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Phalcon\Http\Client\Provider\Exception
     *
     * create by ck 20170323
     * modify by ck 20170419    更改http请求类
     */
    public function getReplacementsDataAction()
    {
        $this->view->disable();
        $config = Main::getConfigByName('jSpeakReplace');
        $httpClient = (new HttpClient())->setBaseUrl($config['url'])->setHeader('Accept', 'application/json');
        $response   = $httpClient->get('v1/replacements/', ['version' => 0]);
        if($response->isSuccess()){
            $body = $response->toArray();
            $result = $body['replacements'];
            $data = [
                'total' => count($result),
                'rows'  => $result
            ];
            return $this->response->setJsonContent($data);
        }
        return $this->response->setContent($response->body ? $response->body : '无返回信息');
    }

    /**
     * 增加字典白名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Phalcon\Http\Client\Provider\Exception
     *
     * create by ck 20170323
     * modify by ck 20170419    更改http请求类
     */
    public function addReplacementsDataAction()
    {
        $this->view->disable();
        $keys = $this->request->getPost('key');
        $values = $this->request->getPost('value');
        $config = Main::getConfigByName('jSpeakReplace');
        $raw = [];
        foreach($keys as $index => $key){
            if(!$key) continue;
            $raw[] = ['key' => $key, 'value' => $values[$index]];
        }
        $httpClient = (new HttpClient())->setBaseUrl($config['url'])->setHeader('Content-Type', 'application/json');
        $response   = $httpClient->postJson('v1/replacements/', $raw);
        return $this->response->setContent($response->isSuccess() ? 'success' : $response->body);
    }

    /**
     * 删除字典白名单（支持批量）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170323
     * modify by ck 20170419    更改http请求类
     * modify by ck 20170811    更改为数组传递
     * modify by ck 20180529    添加实体转义
     */
    public function delReplacementsDataAction()
    {
        $this->view->disable();
        $keys = $this->request->getPost('ids', 'string');
        $config = Main::getConfigByName('jSpeakReplace');
        $httpClient = (new HttpClient())->setBaseUrl($config['url']);
        $error = [];
        foreach($keys as $key){
            if(!$key) continue;
            $response = $httpClient->delete('v1/replacements/', [
                'key'   => htmlspecialchars_decode($key, ENT_QUOTES)
            ]);
            !$response->isSuccess() and $error[$key] = $response;
        }
        if($error){
            return $this->response->setJsonContent($error);
        }
        else{
            return $this->response->setContent('删除成功！');
        }
    }

}

